#pragma once

#include <iostream>
#include <string>
#include <unordered_map>

#include "TcpServer.hpp"
#include "HttpProtocal.hpp"

using namespace TcpServerModule;

using http_heander_t = std::function<void(HttpRequest &, HttpResponse *)>;

class HttpServer
{
public:
    HttpServer(int port)
        : _tsvr(std::make_unique<TcpServer>(port))
    {
    }

    void Resgiter(std::string funcname, http_heander_t func)
    {
        _route[funcname] = func;
    }

    bool SafeCheck(std::string &service)
    {
        auto iter = _route.find(service);
        return iter != _route.end();
    }

    void start()
    {
        _tsvr->InitServer([this](SockPtr sockfd, InetAddr client)
                          { return HandleRequest(sockfd, client); });
        _tsvr->Loop();
    }

    // 处理http
    bool HandleRequest(SockPtr sockfd, InetAddr client)
    {
        LOG(LogLevel::DEBUG) << "HttpServer:get a client " << sockfd->fd() << " addr info: " << client.Addr();
        std::string http_request;
        sockfd->Recv(&http_request);
        // LOG(LogLevel::DEBUG) << "HttpServer:recv http request: \n" << http_request;
        HttpRequest req;
        req.Deserialize(http_request);
        HttpResponse resp;
        // 请求应该分成两类：1.请求一般的静态资源。2.提交参数，携带参数，需要我们进行交互设置
        if (req.IsHasArgs())
        {
            // 2.提交参数，携带参数，需要我们进行交互设置
            std::string service = req.Path();
            LOG(LogLevel::DEBUG) << " service: " << service;

            if (SafeCheck(service))
            {
                _route[req.Path()](req, &resp);
            }
            else
            {
                resp.Build(req);
            }
        }
        else
        {
            // 处理静态资源请求
            resp.Build(req);
        }
        std::string resp_str;
        resp.Serialize(&resp_str);
        //req.Print();
        sockfd->Send(resp_str);
        return true;
    }

    ~HttpServer() {}

private:
    std::unique_ptr<TcpServer> _tsvr;
    std::unordered_map<std::string, http_heander_t> _route; // 功能路由表
};
